using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Linq;
using User.API.Data;

namespace User.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<UserContext>(options =>
            {
                options.UseMySQL(Configuration.GetConnectionString("MysqlUser"));
            });
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env,ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();
            InitUserDataBase(app);
            //UserContextSeed.SeedAsync(app, loggerFactory).Wait();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        public void InitUserDataBase(IApplicationBuilder app, int retry = 0)
        {
            using (var scope = app.ApplicationServices.CreateScope())
            {
                try
                {
                    System.Console.WriteLine($"retry:{retry}");

                    var userContext = scope.ServiceProvider.GetRequiredService<UserContext>();

                    userContext.Database.Migrate();
                    if (!userContext.Users.Any())
                    {
                        System.Console.WriteLine($"createuser:{retry}");
                        userContext.Users.Add(new Model.AppUser { Name = "jesse" });
                        userContext.SaveChanges();
                    }
                }
                catch
                {
                    System.Threading.Thread.Sleep(1000);
                    System.Console.WriteLine($"retryex:{retry}");
                    if (retry++ < 100)
                    {
                        InitUserDataBase(app, retry);
                    }
                }
            }
        }
    }
}
